package com.example.springboot.config.responseadvice;

import com.example.springboot.entity.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/11/26 14:50
 */
@ControllerAdvice
public class FeignResponseAdvice implements ResponseBodyAdvice<Object> {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        boolean feign = serverHttpRequest.getHeaders().containsKey("feign");
        if (feign) {
            // feign直接返回
            return o;
        }
        if (o instanceof String) {
            return objectMapper.writeValueAsString(ResultData.ok(o));
        }
        if (o instanceof ResultData) {
            return o;
        }
        return ResultData.ok(o);
    }
}
